package com.bf.electroplating.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.entity.Warning;
import com.bf.electroplating.pojo.vo.warning.*;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.IFrontWarningService;
import com.bf.electroplating.service.IWarningService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 前端预警信息服务实现类
 */
@Slf4j
@Service
public class FrontWarningServiceImpl implements IFrontWarningService {

    @Autowired
    private IWarningService warningService;
    @Resource
    private ComCompanyService comCompanyService;

    @Override
    public WarningDataVO getWarningData(WarningQueryDTO queryDTO) {
        WarningDataVO data = new WarningDataVO();
        
        // 获取预警统计信息
        WarningStatisticsVO statistics = getWarningStatistics(queryDTO);
        data.setStatistics(statistics);
        
        // 获取预警列表分页数据
        Page<WarningListVO> warningList = getWarningList(queryDTO);
        data.setWarningList(warningList);
        
        return data;
    }

    @Override
    public boolean handleWarning(String warningId, String handleRemark) {
        try {
            Warning warning = warningService.getById(warningId);
            if (warning != null) {
                warning.setHandleStatus("1"); // 已处理
                warning.setHandleBy(UserContext.getUser() != null ? 
                    UserContext.getUser().getUserName() : "系统管理员");
                warning.setHandleTime(LocalDateTime.now());
                warning.setHandleRemark(handleRemark);
                warning.setUpdateTime(LocalDateTime.now());
                
                return warningService.updateById(warning);
            }
            return false;
        } catch (Exception e) {
            log.error("处理预警失败：{}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 获取预警统计信息
     */
    private WarningStatisticsVO getWarningStatistics(WarningQueryDTO queryDTO) {
        WarningStatisticsVO statistics = new WarningStatisticsVO();
        
        // 构建基础查询条件
        LambdaQueryWrapper<Warning> baseWrapper = buildBaseWrapper(queryDTO);
        
        // 总预警数
        Long totalCount = warningService.count(baseWrapper);
        statistics.setTotalCount(totalCount);
        
        // 未处理预警数
        LambdaQueryWrapper<Warning> pendingWrapper = buildBaseWrapper(queryDTO);
        pendingWrapper.eq(Warning::getHandleStatus, "0");
        Long pendingCount = warningService.count(pendingWrapper);
        statistics.setPendingCount(pendingCount);
        
        // 已处理预警数
        statistics.setHandledCount(totalCount - pendingCount);
        
        // 按模块统计
        statistics.setProductionFacilityCount(getCountByModule(queryDTO, "生产设施用电量监控"));
        statistics.setWasteGasFacilityCount(getCountByModule(queryDTO, "废气处理设施用电量监控"));
        statistics.setWasteGasAlarmCount(getCountByModule(queryDTO, "废气处理设施"));
        statistics.setRainwaterPhCount(getCountByWarningFactor(queryDTO, "PH"));
        statistics.setRainwaterConductivityCount(getCountByWarningFactor(queryDTO, "电导率"));
        
        return statistics;
    }

    /**
     * 获取预警列表分页数据
     */
    private Page<WarningListVO> getWarningList(WarningQueryDTO queryDTO) {
        Page<Warning> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        
        LambdaQueryWrapper<Warning> wrapper = buildBaseWrapper(queryDTO);
        wrapper.orderByDesc(Warning::getWarningTime);
        String companyName = null;
        if (!com.alibaba.excel.util.StringUtils.isEmpty(queryDTO.getCompanyId())) {
            ComCompany company=comCompanyService.getById(queryDTO.getCompanyId());
            if (company!=null) {
                companyName=company.getCompanyName();
            }
        }
        if (!com.alibaba.excel.util.StringUtils.isEmpty(companyName)) {
            wrapper.eq(Warning::getCompanyName, companyName);
        }
        Page<Warning> warningPage = warningService.page(page, wrapper);
        
        // 转换为VO
        Page<WarningListVO> voPage = new Page<>();
        BeanUtils.copyProperties(warningPage, voPage, "records");
        
        List<WarningListVO> voList = new ArrayList<>();
        for (Warning warning : warningPage.getRecords()) {
            WarningListVO vo = new WarningListVO();
            BeanUtils.copyProperties(warning, vo);
            
            // 设置处理状态文本
            vo.setHandleStatusText("0".equals(warning.getHandleStatus()) ? "待处置" : "已处置");
            
            // 设置设备名称（从预警内容中提取或使用默认值）
            vo.setDeviceName(extractDeviceName(warning.getWarningContent()));
            
            // 设置预警分析（可以根据实际业务逻辑生成）
            vo.setWarningAnalysis(generateWarningAnalysis(warning));
            vo.setWarningTime(warning.getWarningTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            voList.add(vo);
        }
        
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 构建基础查询条件
     */
    private LambdaQueryWrapper<Warning> buildBaseWrapper(WarningQueryDTO queryDTO) {
        LambdaQueryWrapper<Warning> wrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(queryDTO.getModule())) {
            wrapper.eq(Warning::getModule, queryDTO.getModule());
        }
        
        if (StringUtils.isNotBlank(queryDTO.getWarningType())) {
            wrapper.eq(Warning::getWarningType, queryDTO.getWarningType());
        }
        
        if (StringUtils.isNotBlank(queryDTO.getWarningLevel())) {
            wrapper.eq(Warning::getWarningLevel, queryDTO.getWarningLevel());
        }
        
        if (StringUtils.isNotBlank(queryDTO.getHandleStatus())) {
            wrapper.eq(Warning::getHandleStatus, queryDTO.getHandleStatus());
        }
        

        if (StringUtils.isNotBlank(queryDTO.getParkId())) {
            wrapper.eq(Warning::getParkId, queryDTO.getParkId());
        }
        
        if (queryDTO.getStartTime() != null) {
            wrapper.ge(Warning::getWarningTime, queryDTO.getStartTime());
        }
        
        if (queryDTO.getEndTime() != null) {
            wrapper.le(Warning::getWarningTime, queryDTO.getEndTime());
        }
        
        if (StringUtils.isNotBlank(queryDTO.getKeyword())) {
            wrapper.and(w -> w.like(Warning::getWarningContent, queryDTO.getKeyword())
                    .or().like(Warning::getCompanyName, queryDTO.getKeyword())
                    .or().like(Warning::getWarningFactor, queryDTO.getKeyword()));
        }
        
        // 排除已删除的记录
        wrapper.eq(Warning::getDelFlag, "0");
        
        return wrapper;
    }

    /**
     * 根据模块统计预警数量
     */
    private Long getCountByModule(WarningQueryDTO queryDTO, String module) {
        LambdaQueryWrapper<Warning> wrapper = buildBaseWrapper(queryDTO);
        wrapper.eq(Warning::getModule, module);
        return warningService.count(wrapper);
    }

    /**
     * 根据预警因子统计预警数量
     */
    private Long getCountByWarningFactor(WarningQueryDTO queryDTO, String warningFactor) {
        LambdaQueryWrapper<Warning> wrapper = buildBaseWrapper(queryDTO);
        wrapper.like(Warning::getWarningFactor, warningFactor);
        return warningService.count(wrapper);
    }

    /**
     * 从预警内容中提取设备名称
     */
    private String extractDeviceName(String warningContent) {
        if (StringUtils.isBlank(warningContent)) {
            return "";
        }
        
        // 简单的设备名称提取逻辑，可以根据实际需求调整
        if (warningContent.contains("雨水自动控制")) {
            return "雨水自动控制设备";
        } else if (warningContent.contains("废气处理")) {
            return "废气处理设施";
        } else if (warningContent.contains("用电量")) {
            return "用电监控设备";
        }
        
        return "监控设备";
    }

    /**
     * 生成预警分析
     */
    private String generateWarningAnalysis(Warning warning) {
        StringBuilder analysis = new StringBuilder();
        
        if (warning.getWarningValue() != null && warning.getWarningThreshold() != null) {
            analysis.append("监测值：").append(warning.getWarningValue())
                   .append("，阈值：").append(warning.getWarningThreshold());
            
            if (warning.getWarningValue().compareTo(warning.getWarningThreshold()) > 0) {
                analysis.append("，超出阈值");
            }
        }
        
        if (StringUtils.isNotBlank(warning.getWarningFactor())) {
            analysis.append("，监测因子：").append(warning.getWarningFactor());
        }
        
        return analysis.length() > 0 ? analysis.toString() : "系统自动分析";
    }
}
